<template>
  <div class="dashboard-container">
    <!-- github 角标 -->
    <!-- <github-corner class="github-corner" /> -->

    <el-row class="h-132px" :gutter="10">
      <el-col :span="14" :xs="24">
        <el-card shadow="never" class="greeting1">
          <div class="flex-x-start">
            <!-- <img
              class="w80px h80px rounded-full"
              :src="userStore.userInfo.sysUser.name + '?imageView2/1/w/80/h/80'"
            /> -->
            <div class="ml-5">
              <p class="greeting-title">{{ greetings }}</p>
              <p class="greeting-title text-sm text-gray">
                今日天气晴朗，气温在15℃至25℃之间，东南风。
              </p>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="10" :xs="24">
        <el-card shadow="never" class="greeting2">
          <div class="flex-x-start">
            <div class="ml-5">
              <p>{{ curNickName + ' 您好，祝您开心每一天' }}</p>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="10" class="mt-5">
      <!-- 访问趋势统计图 -->
      <el-col :xs="24" :span="16">
        <el-card>
          <template #header>
            <div class="flex-x-between">
              <span>火电分类图表</span>
              <!-- <el-radio-group v-model="visitTrendDateRange" size="small">
                <el-radio-button label="近7天" :value="7" />
                <el-radio-button label="近30天" :value="30" />
              </el-radio-group> -->
            </div>
          </template>
          <div id="chart2" class="chart-area"></div>
          <!-- <ECharts :options="visitTrendChartOptions" height="400px" /> -->
        </el-card>
      </el-col>
      <!-- 最新动态 -->
      <el-col :xs="24" :span="8">
        <el-card>
          <template #header>
            <div class="flex-x-between">
              <span class="header-title">最新动态</span>
              <!-- <el-link
                type="primary"
                :underline="false"
                href="https://gitee.com/youlaiorg/vue3-element-admin/releases"
                target="_blank"
              >
                完整记录
                <el-icon class="link-icon"><TopRight /></el-icon>
              </el-link> -->
            </div>
          </template>

          <el-scrollbar height="515px">
            <el-timeline class="p-3">
              <el-timeline-item
                v-for="(item, index) in vesionList"
                :key="index"
                :timestamp="item.date"
                placement="top"
                :color="index === 0 ? '#67C23A' : '#909399'"
                :hollow="index !== 0"
                size="large"
              >
                <div class="version-item" :class="{ 'latest-item': index === 0 }">
                  <div>
                    <el-text tag="strong">{{ item.title }}</el-text>
                    <el-tag v-if="item.tag" :type="index === 0 ? 'success' : 'info'" size="small">
                      {{ item.tag }}
                    </el-tag>
                  </div>

                  <el-text class="version-content">{{ item.content }}</el-text>

                  <div v-if="item.link">
                    <el-link
                      :type="index === 0 ? 'primary' : 'info'"
                      :href="item.link"
                      target="_blank"
                      :underline="false"
                    >
                      详情
                      <el-icon class="link-icon"><TopRight /></el-icon>
                    </el-link>
                  </div>
                </div>
              </el-timeline-item>
            </el-timeline>
          </el-scrollbar>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: 'Dashboard',
  inheritAttrs: false,
});

import { dayjs } from 'element-plus';
import LogAPI, { VisitStatsVO, VisitTrendVO } from '@/api/system/log.api';
import { useUserStore } from '@/store';
import VChart from '@visactor/vchart';

interface VersionItem {
  id: string;
  title: string; // 版本标题（如：v2.4.0）
  date: string; // 发布时间
  content: string; // 版本描述
  link?: string; // 详情链接
  tag?: string; // 版本标签（可选）
}

const userStore = useUserStore();
const curNickName = computed(() => userStore?.userInfo?.sysUser?.name);
// 当前通知公告列表
const vesionList = ref<VersionItem[]>([
  {
    id: '1',
    title: '202505批次',
    date: '2025-05-01 00:00:00',
    content: '202505批次下发，预计2025年5月31日完成。',
    // link: 'https://gitee.com/youlaiorg/vue3-element-admin/releases',
    tag: '里程碑',
  },
  {
    id: '1',
    title: '202504批次',
    date: '2025-04-01 00:00:00',
    content: '202504批次下发，预计2025年4月31日完成。',
    // link: 'https://gitee.com/youlaiorg/vue3-element-admin/releases',
    tag: '里程碑',
  },
  {
    id: '1',
    title: '202503批次',
    date: '2025-03-01 00:00:00',
    content: '202503批次下发，预计2025年3月31日完成。',
    // link: 'https://gitee.com/youlaiorg/vue3-element-admin/releases',
    tag: '里程碑',
  },
]);

// 当前时间（用于计算问候语）
const currentDate = new Date();

// 问候语：根据当前小时返回不同问候语
const greetings = computed(() => {
  const hours = currentDate.getHours();
  const nickname = userStore?.userInfo?.sysUser?.name;
  if (hours >= 6 && hours < 8) {
    return '晨起披衣出草堂，轩窗已自喜微凉🌅！';
  } else if (hours >= 8 && hours < 12) {
    return `上午好，${nickname}！`;
  } else if (hours >= 12 && hours < 18) {
    return `下午好，${nickname}！`;
  } else if (hours >= 18 && hours < 24) {
    return `晚上好，${nickname}！`;
  } else {
    return '偷偷向银河要了一把碎星，只等你闭上眼睛撒入你的梦中，晚安🌛！';
  }
});

// 访客统计数据加载状态
const visitStatsLoading = ref(true);
// 访客统计数据
const visitStatsData = ref<VisitStatsVO>({
  todayUvCount: 0,
  uvGrowthRate: 0,
  totalUvCount: 0,
  todayPvCount: 0,
  pvGrowthRate: 0,
  totalPvCount: 0,
});

// 访问趋势日期范围（单位：天）
const visitTrendDateRange = ref(7);
// 访问趋势图表配置
const visitTrendChartOptions = ref();
let vchartRef: any = null; // vcharts 实例

const initChart2 = () => {
  const spec: any = {
    type: 'line',
    smooth: true,
    data: {
      values: [
        { type: '2024-11', country: '煤电', value: 4229 },
        { type: '2024-11', country: '风电', value: 4376 },
        { type: '2024-11', country: '光伏', value: 3054 },
        { type: '2024-11', country: '其他', value: 2814 },
        { type: '2024-12', country: '煤电', value: 3932 },
        { type: '2024-12', country: '风电', value: 3987 },
        { type: '2024-12', country: '光伏', value: 5067 },
        { type: '2024-12', country: '其他', value: 13012 },
        { type: '2025-01', country: '煤电', value: 5221 },
        { type: '2025-01', country: '风电', value: 3574 },
        { type: '2025-01', country: '光伏', value: 7004 },
        { type: '2025-01', country: '其他', value: 11624 },
        { type: '2025-02', country: '煤电', value: 9256 },
        { type: '2025-02', country: '风电', value: 4376 },
        { type: '2025-02', country: '光伏', value: 9054 },
        { type: '2025-02', country: '其他', value: 8814 },
        { type: '2025-03', country: '煤电', value: 3308 },
        { type: '2025-03', country: '风电', value: 4572 },
        { type: '2025-03', country: '光伏', value: 12043 },
        { type: '2025-03', country: '其他', value: 12998 },
      ],
    },
    // series: [
    //   {
    //     type: 'line',
    //     dataId: 'data1',
    //     xField: 'country',
    //     yField: 'value',
    //     smooth: true, // 启用平滑效果
    //     smoothMonotone: 'x', // 可选，控制曲线单调性
    //   },
    // ],
    title: {
      visible: true,
      text: '数据分类筛选',
    },
    stack: false, // 是否对数据进行堆叠处理
    xField: 'type',
    yAxis: {
      name: '消纳率 %',
    },
    xAxis: {
      name: '储能配置',
    },
    yField: 'value',
    seriesField: 'country', // 系列分组字段，默认会用于颜色映射
    lineLabel: { visible: true },
    legends: [{ visible: true, position: 'middle', orient: 'bottom' }],
  };

  if (vchartRef) {
    vchartRef?.release();
  }

  vchartRef = new VChart(spec, { dom: 'chart2' });
  vchartRef.renderSync();
};

/**
 * 获取访客统计数据
 */
const fetchVisitStatsData = () => {
  // LogAPI.getVisitStats()
  //   .then((data) => {
  //     visitStatsData.value = data;
  //   })
  //   .finally(() => {
  //     visitStatsLoading.value = false;
  //   });
};

/**
 * 获取访问趋势数据，并更新图表配置
 */
const fetchVisitTrendData = () => {
  const startDate = dayjs()
    .subtract(visitTrendDateRange.value - 1, 'day')
    .toDate();
  const endDate = new Date();

  // LogAPI.getVisitTrend({
  //   startDate: dayjs(startDate).format("YYYY-MM-DD"),
  //   endDate: dayjs(endDate).format("YYYY-MM-DD"),
  // }).then((data) => {
  //   updateVisitTrendChartOptions(data);
  // });
};

/**
 * 更新访问趋势图表的配置项
 *
 * @param data - 访问趋势数据
 */
const updateVisitTrendChartOptions = (data: VisitTrendVO) => {
  console.log('Updating visit trend chart options');

  visitTrendChartOptions.value = {
    tooltip: {
      trigger: 'axis',
    },
    legend: {
      data: ['浏览量(PV)', '访客数(UV)'],
      bottom: 0,
    },
    grid: {
      left: '1%',
      right: '5%',
      bottom: '10%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      data: data.dates,
    },
    yAxis: {
      type: 'value',
      splitLine: {
        show: true,
        lineStyle: {
          type: 'dashed',
        },
      },
    },
    series: [
      {
        name: '浏览量(PV)',
        type: 'line',
        data: data.pvList,
        areaStyle: {
          color: 'rgba(64, 158, 255, 0.1)',
        },
        smooth: true,
        itemStyle: {
          color: '#4080FF',
        },
        lineStyle: {
          color: '#4080FF',
        },
      },
      {
        name: '访客数(UV)',
        type: 'line',
        data: data.ipList,
        areaStyle: {
          color: 'rgba(103, 194, 58, 0.1)',
        },
        smooth: true,
        itemStyle: {
          color: '#67C23A',
        },
        lineStyle: {
          color: '#67C23A',
        },
      },
    ],
  };
};

/**
 * 根据增长率计算对应的 CSS 类名
 *
 * @param growthRate - 增长率数值
 */
const computeGrowthRateClass = (growthRate?: number): string => {
  if (!growthRate) {
    return 'color-[--el-color-info]';
  }
  if (growthRate > 0) {
    return 'color-[--el-color-danger]';
  } else if (growthRate < 0) {
    return 'color-[--el-color-success]';
  } else {
    return 'color-[--el-color-info]';
  }
};

// 监听访问趋势日期范围的变化，重新获取趋势数据
watch(
  () => visitTrendDateRange.value,
  (newVal) => {
    console.log('Visit trend date range changed:', newVal);
    fetchVisitTrendData();
  },
  { immediate: true }
);

// 组件挂载后加载访客统计数据和通知公告数据
onActivated(() => {
  fetchVisitStatsData();
  initChart2();
});

onDeactivated(() => {
  // 销毁图表实例
  vchartRef?.release();
});
</script>

<style lang="scss" scoped>
.dashboard-container {
  position: relative;
  padding: 24px;

  .greeting1 {
    height: 100%;
    // background: linear-gradient(135deg, #1d75fa 0%, rgba(61, 136, 249, 0.5) 100%);
    background: url('@/assets/images/greet1.png') no-repeat center;
    background-size: cover;
    border-radius: 5px;
  }
  .greeting2 {
    height: 100%;
    // background: linear-gradient(135deg, rgba(61, 136, 249, 0.5) 0%, transparent 100%);
    background: url('@/assets/images/greet2.png') no-repeat center;
    background-size: cover;
    border-radius: 5px;
  }
  .greeting-title {
    color: #f4f8ff;
  }
  .github-corner {
    position: absolute;
    top: 0;
    right: 0;
    z-index: 1;
    border: 0;
  }
  .chart-area {
    width: 100%;
    height: 500px;
    margin-bottom: 15px;
  }
  .version-item {
    padding: 16px;
    margin-bottom: 12px;
    background: var(--el-fill-color-lighter);
    border-radius: 8px;
    transition: all 0.2s;

    &.latest-item {
      background: var(--el-color-primary-light-9);
      border: 1px solid var(--el-color-primary-light-5);
    }
    &:hover {
      transform: translateX(5px);
    }
    .version-content {
      margin-bottom: 12px;
      font-size: 13px;
      line-height: 1.5;
      color: var(--el-text-color-secondary);
    }
  }
}
</style>
